package com.lzc.jobrecomendbackend.controller;

import com.lzc.jobrecomendbackend.common.Result;
import com.lzc.jobrecomendbackend.model.User;
import com.lzc.jobrecomendbackend.model.dto.LoginDTO;
import com.lzc.jobrecomendbackend.model.dto.UserInfoDTO;
import com.lzc.jobrecomendbackend.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public Result<UserInfoDTO> register(@RequestBody User user) {
        try {
            User registeredUser = userService.register(user);
            UserInfoDTO userInfoDTO = convertToDTO(registeredUser);
            return Result.success("注册成功", userInfoDTO);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result<UserInfoDTO> login(@RequestBody LoginDTO loginDTO) {
        try {
            User user = userService.login(loginDTO.getUsername(), loginDTO.getPassword());
            UserInfoDTO userInfoDTO = convertToDTO(user);
            return Result.success("登录成功", userInfoDTO);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取用户信息
     */
    @GetMapping("/info/{userId}")
    public Result<UserInfoDTO> getUserInfo(@PathVariable String userId) {
        try {
            User user = userService.getUserInfo(userId);
            UserInfoDTO userInfoDTO = convertToDTO(user);
            return Result.success(userInfoDTO);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 更新用户信息
     */
    @PutMapping("/update")
    public Result<UserInfoDTO> updateUserInfo(@RequestBody User user) {
        try {
            User updatedUser = userService.updateUserInfo(user);
            UserInfoDTO userInfoDTO = convertToDTO(updatedUser);
            return Result.success("更新成功", userInfoDTO);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 将User对象转换为UserInfoDTO对象
     */
    private UserInfoDTO convertToDTO(User user) {
        UserInfoDTO userInfoDTO = new UserInfoDTO();
        BeanUtils.copyProperties(user, userInfoDTO);
        return userInfoDTO;
    }
} 